<?php
namespace app\admin\controller;
use app\common\controller\Com;

class Auth extends Com
{
    public function initialize(){
        self::check_login();

        //超级管理员不需要验证
        if(ISADMIN)return true;
        //公共模块不验证权限
        if($this->public_is)return false;

        //权限验证
        $model      = request()->module();
        $controller = request()->controller();
        $action     = request()->action();

        //公共操作不需要验证
        $_public_action=$this->public_action;
        if($_public_action && is_array($_public_action) && in_array(strtolower($action), $_public_action))return true;

        $rule  = strtolower($model.'/'.$controller.'/'.$action);

        //验证是否有访问权限
        if(self::checkRule($rule))return true ;

        $this->error('您没有该功能的访问权限');
    }


    //判断用户是否已经登陆
    final public function check_login() {
        $uid = is_login();
        if(!$uid)return $this->redirect('/'.get_admin_login_file().'/pub/login');
        define('UID',$uid);

        //超级管理账号id
        $ids=config("common.admininstrator_ids");
        ($ids && in_array(UID,$ids))?define('ISADMIN',1):define('ISADMIN',0);

        if(!config("common.auth_ondb_everytime"))return;

        $ainfo=model('admin')->where('id','=',$uid)->field('state')->find();
        if(empty($ainfo) || 0==$ainfo['state']){
            $save_pre = config("common.admin_login_save_pre");
            cookie($save_pre.'_auth', null);
            cookie($save_pre.'_auth_sign', null);
            session($save_pre.'_auth', null);
            session($save_pre.'_auth_sign', null);
            session($save_pre.'_rules',null);  //当前账号拥有的权限ids
            session($save_pre.'_author',null); //当前账号已验证的权限
            session('__forward__',null);

            return $this->redirect('/'.get_admin_login_file().'/pub/login');
        }
    }


    /**
     * 权限检测
     * @param string  $rule    权限节点
     */
    final protected function checkRule($rule){
        //检查权限是否已经检测过
        $save_pre = config("common.admin_login_save_pre");
        $author = session($save_pre.'_author');
        $author_ary = $author?unserialize($author):false;
        if(is_array($author_ary) && in_array(md5($rule), $author_ary))return true ;

        //获取当前账号拥有的权限节点
        $ids = get_rules();
        if(empty($ids))return false;

        //查询当前权限节点的ID值
        $map[]=['path','=',$rule];
        $nid = model('menu')->where($map)->value('id');
        if(empty($nid))return false;

        //权限存在，保存权限节点，下次访问时不再验证
        if(in_array($nid,$ids)){
            $author_ary[] = md5($rule);
            session($save_pre.'_author',serialize($author_ary));
            return true;
        }

        return false;
    }


}
